package cn.controller;

import cn.entity.Users;
import cn.service.UsersService;
import cn.util.Const;
import cn.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
//@Scope("prototype")
@RequestMapping("/users")
public class UsersController {//SSM
    @Autowired
    UsersService usersService;
    @RequestMapping("admin/login")
    public String login(String username, String password, HttpSession session,HttpServletResponse response) throws IOException {
        PrintWriter out=response.getWriter();
        //int n=5/0;
        String md5pass= MD5Util.getMD5(password);
        Users users=usersService.login(username, md5pass,0);
        if(users!=null){
            //将用户放入session
            session.setAttribute("users", users);
            session.setAttribute("role", 0);
            //成功,重定向,2次请求，重新发起的,新闻列表
            return "redirect:/kind/admin/list";
        }else{
            out.print("<script>alert('用户名或者密码错误222');location.href='"+Const.ROOT+"admin/login.jsp';</script>");
            out.close();
            return null;
        }
    }
    @RequestMapping("reg")
    public String reg(Users users, HttpServletResponse response) throws IOException {
        PrintWriter out=response.getWriter();

        users.setPassword(MD5Util.getMD5(users.getPassword()));
        users.setIsdel(0);
        int n=usersService.insert(users);
        if(n>0){
            return "redirect:/login.jsp";
        }else{
            out.print("<script>alert('注册失败');location.href='"+Const.ROOT+"login.jsp';</script>");
        }
        return null;
    }

    @RequestMapping("admin/logout")
    public String logout(HttpSession session) throws IOException {
        session.invalidate();
        return "redirect:/admin/login.jsp";
    }

    //局部异常处理
//    @ExceptionHandler
//    public String parseError(Exception ex, HttpServletRequest request){
//        request.setAttribute("errorMsg",ex.getMessage());
//        return "500";
//    }
}
